<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h2>个人资料</h2>
        </div>
      </template>
      
      <el-form 
        ref="formRef"
        :model="userForm"
        :rules="rules"
        label-width="100px"
        class="profile-form"
      >
        <!-- 头像上传 -->
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="{ Authorization: `Bearer ${token}` }"
          >
            <el-avatar
              v-if="userForm.avatar"
              :src="getImageUrl(userForm.avatar)"
              :size="100"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">点击上传头像</div>
        </el-form-item>

        <!-- 用户名（不可修改） -->
        <el-form-item label="用户名">
          <el-input v-model="userForm.username" disabled />
        </el-form-item>

        <!-- 昵称 -->
        <el-form-item label="昵称" prop="name">
          <el-input v-model="userForm.name" />
        </el-form-item>

        <!-- 修改密码 -->
        <el-form-item label="原密码" prop="oldPassword">
          <el-input 
            v-model="userForm.oldPassword"
            type="password"
            show-password
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="userForm.newPassword"
            type="password"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="userForm.confirmPassword"
            type="password"
            show-password
          />
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存修改</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import request from '@/utils/request'
import Cookies from 'js-cookie'

const formRef = ref(null)
const token = Cookies.get('token')
const baseUrl = import.meta.env.VITE_API_URL || ''

// 计算上传URL
const uploadUrl = computed(() => `${baseUrl}/api/file/upload`)

// 表单数据
const userForm = reactive({
  username: '',
  name: '',
  avatar: '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  oldPassword: [
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  newPassword: [
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    {
      validator: (rule, value, callback) => {
        if (value && value !== userForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 初始化用户数据
const initUserData = () => {
  const userInfo = JSON.parse(Cookies.get('userInfo') || '{}')
  userForm.username = userInfo.username || ''
  userForm.name = userInfo.name || ''
  userForm.avatar = userInfo.avatar || ''
}

// 获取图片URL
const getImageUrl = (url) => {
  if (!url) return ''
  return url
}

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传头像图片只能是图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 头像上传成功的回调
const handleAvatarSuccess = (res) => {
  if (res.code === 200) {
    // 直接使用返回的URL
    userForm.avatar = res.data
    // 更新本地存储的用户信息
    const userInfo = JSON.parse(Cookies.get('userInfo') || '{}')
    userInfo.avatar = res.data
    Cookies.set('userInfo', JSON.stringify(userInfo))
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error('头像上传失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 获取当前用户ID
        const userInfo = JSON.parse(Cookies.get('userInfo') || '{}')
        if (!userInfo.id) {
          ElMessage.error('用户信息异常，请重新登录')
          return
        }

        // 构建更新数据
        const updateData = {
          realName: userForm.name,
          avatar: userForm.avatar  // 直接使用完整URL
        }
        
        // 如果填写了密码，添加密码相关字段
        if (userForm.oldPassword && userForm.newPassword) {
          updateData.oldPassword = userForm.oldPassword
          updateData.newPassword = userForm.newPassword
        }
        
        const res = await request.put(`/admin/user/${userInfo.id}/profile`, updateData)
        
        if (res.code === 200) {
          ElMessage.success('个人资料更新成功')
          // 更新本地存储的用户信息
          userInfo.name = userForm.name
          userInfo.avatar = userForm.avatar
          Cookies.set('userInfo', JSON.stringify(userInfo))
          
          // 清空密码字段
          userForm.oldPassword = ''
          userForm.newPassword = ''
          userForm.confirmPassword = ''
        }
      } catch (error) {
        console.error('更新个人资料失败:', error)
        ElMessage.error('更新失败，请重试')
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
    initUserData()
  }
}

// 初始化
initUserData()
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.profile-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.profile-form {
  margin-top: 20px;
}

.avatar-uploader {
  text-align: center;
}

.avatar {
  display: block;
  margin: 0 auto;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  border: 1px dashed var(--el-border-color);
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.avatar-uploader-icon:hover {
  border-color: var(--el-color-primary);
  color: var(--el-color-primary);
}

.upload-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 8px;
  text-align: center;
}

:deep(.el-form-item__content) {
  max-width: 400px;
}
</style> 